package com.ghao.douban.realm;

import com.ghao.douban.Entity.SysUser;
import com.ghao.douban.mapper.SysUserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //需要明白的是能拿到权限的前提是通过了认证
        //所以可以拿到username
        String username = (String) principalCollection.getPrimaryPrincipal();
        String perm = sysUserMapper.selectPermByName(username);

        //将拿到的权限放入权限器中，由shiro自己处理
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermission(perm);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //请求转过来的token含有前端传入的username和password
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //通过username在数据库中查询password方便待会比较
        String username = token.getUsername();
        String credential = sysUserMapper.selectPasswordByName(username);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, credential, this.getName());
        return authenticationInfo;
    }
}
